using Lzfy_His_Service.Models;
using Lzfy_His_Service.Services;
using System.Data;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace Lzfy_His_Service.Services
{
    public class AccountOpLogService : IAccountOpLogService
    {
        private readonly string _connectionString;
        private readonly ILogger<AccountOpLogService> _logger;

        public AccountOpLogService(
            IConfiguration configuration,
            ILogger<AccountOpLogService> logger)
        {
            _connectionString = configuration.GetConnectionString("DefaultConnection") 
                ?? throw new InvalidOperationException("数据库连接字符串未配置");
            _logger = logger;
        }

        /// <summary>
        /// 创建账户操作日志
        /// </summary>
        /// <param name="request">创建请求</param>
        /// <returns>创建的日志ID</returns>
        public async Task<AccountOpLogResponse> CreateAsync(AccountOpLogCreateRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            try
            {
                using var connection = new SqlConnection(_connectionString);
                await connection.OpenAsync();
                
                const string sql = @"
                    INSERT INTO lzfy_account_op_logs 
                    (funcname, apiurl, accountid, requestbody, responsedata, mobile, username, fullname)
                    VALUES 
                    (@FuncName, @ApiUrl, @AccountId, @RequestBody, @ResponseData, @Mobile, @Username, @Fullname);
                    SELECT CAST(SCOPE_IDENTITY() as int);";

                using var command = new SqlCommand(sql, (SqlConnection)connection);
                command.Parameters.AddWithValue("@FuncName", (object?)request.FuncName ?? DBNull.Value);
                command.Parameters.AddWithValue("@ApiUrl", (object?)request.ApiUrl ?? DBNull.Value);
                command.Parameters.AddWithValue("@AccountId", (object?)request.AccountId ?? DBNull.Value);
                command.Parameters.AddWithValue("@RequestBody", (object?)request.RequestBody ?? DBNull.Value);
                command.Parameters.AddWithValue("@ResponseData", (object?)request.ResponseData ?? DBNull.Value);
                command.Parameters.AddWithValue("@Mobile", (object?)request.Mobile ?? DBNull.Value);
                command.Parameters.AddWithValue("@Username", (object?)request.Username ?? DBNull.Value);
                command.Parameters.AddWithValue("@Fullname", (object?)request.Fullname ?? DBNull.Value);

                var id = await command.ExecuteScalarAsync();
                
                _logger.LogInformation("创建账户操作日志成功，ID: {Id}, 用户: {Username}, 功能: {FuncName}", 
                    id, request.Username, request.FuncName);

                return new AccountOpLogResponse
                {
                    Success = true,
                    Message = "创建成功",
                    Id = Convert.ToInt32(id)
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建账户操作日志失败，用户: {Username}, 功能: {FuncName}", 
                    request.Username, request.FuncName);
                
                return new AccountOpLogResponse
                {
                    Success = false,
                    Message = $"创建失败: {ex.Message}"
                };
            }
        }
    }
}